package com.atguigu.flink.datastreamapi.transform;

import com.atguigu.flink.function.WaterSensorMapFunction;
import com.atguigu.flink.pojo.WaterSensor;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Smexy on 2022/12/13
 *      希望统计每一种传感器的vc和
 */
public class Demo10_Process2
{
    public static void main(String[] args) {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

                env
                   .socketTextStream("hadoop103", 8888)
                   .map(new WaterSensorMapFunction())
                   .keyBy(WaterSensor::getId)
                   //KeyedProcessFunction<K, I, O>
                   //相同的key一定发送下游的同一个subTask
                   //不同的key，有可能发往下游的同一个subTask
                   .process(new KeyedProcessFunction<String, WaterSensor, String>()
                   {
                       //每一种key有自己累加的变量
                       Map<String,Integer> vcs = new HashMap<>();
                       //int sum = 0;
                       @Override
                       public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {

                           String key = ctx.getCurrentKey();
                           //判断key是什么类型，累加到对应类型之前累加的结果
                           Integer sum = vcs.getOrDefault(key, 0);

                           sum += value.getVc();

                           vcs.put(key,sum);

                           out.collect(key +":" + sum);

                       }
                   }).setParallelism(2)
                   .print();

                try {
                            env.execute();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }


    }
}
